package com.presto.directo.mvvm.viewmodel

import androidx.lifecycle.ViewModelProvider
import com.presto.directo.base.BaseActivity
import com.presto.directo.base.BaseFragment
import com.presto.directo.event.ActionEvent

inline fun <reified T : BaseViewModel> BaseActivity.getViewModel(): T {
    val viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(T::class.java)
    viewModel.setLifecycleOwner(this)
    viewModel.actionLiveData.observe(this, {
        when (it.action) {
            ActionEvent.SHOW_PROGRESS -> showProgress()
            ActionEvent.DISMISS_PROGRESS -> dismissProgress()
            ActionEvent.TOAST -> toast(it.msg)
            ActionEvent.FINISH -> finish()
        }
    })
    return viewModel
}

inline fun <reified T : BaseViewModel> BaseFragment.getViewModel(): T {
    val viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(mActivity.application)).get(T::class.java)
    viewModel.setLifecycleOwner(this)
    viewModel.actionLiveData.observe(this, {
        when (it.action) {
            ActionEvent.SHOW_PROGRESS -> showProgress()
            ActionEvent.DISMISS_PROGRESS -> dismissProgress()
            ActionEvent.TOAST -> toast(it.msg)
            ActionEvent.FINISH -> mActivity.finish()
        }
    })
    return viewModel
}